import { useState, useEffect } from "react";
import { Form, Popconfirm, Space, InputNumber, message, Image, Button, Input, Row, Col, Modal } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { productinboundorderCreateProductOrder, getGoodsSkuPage } from "../service";
import StashSelect from "@/views/components/StashSelect";
import { cloneDeep } from "lodash";
import Style from "./index.module.less";
import { getFmcgpurchasesList } from "@/pages/PurchaseModule/fmcmPurchase/service";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import GoodsListModal from "@/pages/GoodsModule/combinationGoods/component/GoodsListModal";
const AddWarehouseOrderModal = ({ visible, handleCancel, fetchList, warehouseList }) => {
	const [form] = Form.useForm();
	const [selectedWarehouse, setSelectedWarehouse] = useState("");
	const [selectedWarehouseName, setSelectedWarehouseName] = useState("");
	const [goodsList, setGoodsList] = useState([]);
	const [addVisible, setAddVisible] = useState(0);
	const [selectName, setSelectName] = useState("");
	const [warehouseType, setWarehouseType] = useState(null);
	console.log(warehouseList, "warehouseList");
	const columns = [
		{
			title: "供应商",
			dataIndex: "skuName"
		},
		{
			title: "商品图片",
			dataIndex: "image",
			width: 100,
			render: (value, record, i) => <Image width={60} src={value} />
		},
		{
			title: "商品名称",
			dataIndex: "skuName"
		},
		{
			title: "商品编码",
			dataIndex: "skuCode"
		},
		{
			title: "款式编码",
			dataIndex: "spuCode"
		},
		{
			title: "颜色规格",
			dataIndex: "colorSpecifications"
		},
		{
			title: "入库数量",
			dataIndex: "originalNum",
			render: (text, record, index) => (
				<div>
					<InputNumber min={1} value={text} precision={0} onChange={e => handleNumChange(e, record, index)} />
				</div>
			)
		},
		{
			title: "操作",
			width: 150,
			dataIndex: "action",
			key: "action",
			render: (t, r, i) => (
				<span className="opera-span-common">
					<Popconfirm title="确定删除该条数据?" onConfirm={() => delList(r, i)} onCancel={cancel}>
						<a href="#">删除</a>
					</Popconfirm>
				</span>
			)
		}
	];
	const CheckGoodsModalProps = {
		addVisible,
		selectName,
        isNotShow: true,
		handleOk() {},
		handleCancel() {
			setAddVisible(0);
		}
	};
	const handleNumChange = (e, record, index) => {
		console.log(e, record, index, "e, record, index");
		const reg = /^[1-9]\d*$/;
		const val = e;
		if (reg.test(val)) {
			const arr = cloneDeep(goodsList);
			const obj = cloneDeep(record);
			obj.originalNum = val;
			arr.splice(index, 1, obj);
			setGoodsList(arr);
		} else {
			message.info("请输入正整数");
		}
	};
	const onOk = async () => {
		if (goodsList.length === 0) {
			return message.error("请选择商品");
		}
		console.log(goodsList, "goodsList");
		goodsList.map(x => {
			if (x.goodsSkuMatches) {
				const list = x.goodsSkuMatches?.filter(item => item.isDefault === 1)
					? x.goodsSkuMatches?.filter(item => item.isDefault === 1)
					: x?.goodsSkuMatches[0];
				console.log(list, "listssssssssss");
				if (list.length > 0) {
					x.supplierSkuName = list[0].supplierSkuName;
					x.supplierSpuCode = list[0].supplierSpuCode;
					x.supplierName = list[0].supplierName;
					x.supplierSkuImage = list[0].supplierSkuImage;
					x.supplierSkuSpec = list[0].supplierSkuSpecs;
					x.supplierSkuPrice = list[0].supplierSkuPrice;
					x.supplierSkuId = list[0].supplierSkuId;
					x.supplierId = list[0].supplierId;
				}
			}
			x.skuImage = x.image;
			x.originalNum = x.originalNum ? x.originalNum : 1;
			return x;
		});
		const { success } = await productinboundorderCreateProductOrder({
			warehouseId: selectedWarehouse,
			warehouseName: selectedWarehouseName,
			warehouseType: warehouseType,
			productInboundOrderDetailsList: goodsList
		});
		if (success) {
			Modal.info({
				title: '操作提示',
				content: '新建入库单成功',
				onOk() {
					onCancel();
					fetchList();
				}
			})
		}
	};

	const getGoodList = async value => {
		console.log(value, "value");
		const { data, success } = await getGoodsSkuPage({ skuCode: value, type: 1, pageNum: 1, pageSize: 9999 });
		if (data.records && data.records.length > 0) {
			if (success) {
				data.records.map(x => ((x.total = 1), (x.skuId = x.id)));
				const filterLsit = Object.values(
					[...goodsList, ...data.records].reduce((accumulator, currentValue) => {
						if (accumulator[currentValue.id]) {
							accumulator[currentValue.id].total += currentValue.total;
						} else {
							accumulator[currentValue.id] = { ...currentValue };
						}
						return accumulator;
					}, {})
				);
				filterLsit.forEach(i => {
					i.originalNum = i.total;
				});

				setGoodsList(filterLsit);
			}
		} else {
			message.error("输入信息有有误");
		}
	};
	const delList = (record, index, index1) => {
		const arr = cloneDeep(goodsList);
		arr.splice(index, 1);
		setGoodsList(arr);
	};
	const cancel = () => {};

	// 回车搜索商品
	const commonPressEnter = async value => {
		if (value) {
			const { data, success } = await getFmcgpurchasesList({ codes: value?.split(","), pageNum: 1, pageSize: 9999 });
			if (success) {
				if (data && data.records.length > 0) {
					let skuCodeData = data.records.map(x => x.skuCode);

					console.log(skuCodeData, "skuCodeData");
					getGoodList(skuCodeData ? skuCodeData.join(",") : "");
				} else {
					console.log(value, "value11111111111111");
					getGoodList(value);
				}
			} else {
				message.error("输入信息有有误");
			}
			form.setFieldValue("inputValue", "");
		} else {
			message.warning("请输入系统商品编码/商品唯一码");
		}
	};
	const handleChildValue = value => {
		value.map(x => ((x.skuId = x.id), (x.originalNum = x.num ? Number(x.num) : 1)));
		const list = [...value, ...goodsList];
		let filtrLsit = list?.reduce((accumulator, current) => {
			if (!accumulator.has(current.skuId)) {
				accumulator.set(current.skuId, current);
			} else {
				let item = accumulator.get(current.skuId);
				item.originalNum += current.originalNum;
			}
			return accumulator;
		}, new Map());

		filtrLsit = Array.from(filtrLsit.values());
		setGoodsList(filtrLsit);
	};
	const AddHandleClick = name => {
		setSelectName(name);
		setAddVisible(1);
	};
	const handleWarehouseChange = value => {
		setSelectedWarehouse(value.value);
		setSelectedWarehouseName(value.label);
		setWarehouseType(value.title);
	};

	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};

	return (
		<CommonModal
			title={{ title: "新建入库单" }}
			visible={true}
			onOk={onOk}
			onCancel={onCancel}
			width="1200px"
			footer={
				<Row style={{ justifyContent: "end" }}>
					<Col>
						<Space>
							<Button size="middle" onClick={onCancel}>
								取消
							</Button>
							<Button size="middle" type="primary" onClick={onOk}>
								确定
							</Button>
						</Space>
					</Col>
				</Row>
			}
			okText="创建入库单"
		>
			<div className={Style.detail_inner}>
				<SubTitle symbol as="s2" title="设置入仓仓库" wrapStyle={{ marginBottom: 16 }} />
				<Form form={form} name="mark-unuaual-modal" style={{ marginTop: "12px" }}>
					<Row>
						<Col span={6}>
							<Form.Item label="" name="warehouseId">
								<StashSelect
									origin={origin}
									isShow={true}
									value={selectedWarehouse}
									warehouseList={warehouseList.current}
									placeholder={"选择入库仓库"}
									onChange={handleWarehouseChange}
								/>
							</Form.Item>
						</Col>
					</Row>
					<SubTitle symbol as="s2" title="商品设置" wrapStyle={{ marginBottom: 16 }} />
					<div className="flex" style={{ justifyContent: "space-between" }}>
						<Button className="mb10" onClick={() => AddHandleClick("add")}>
							新增商品
						</Button>
						<Form.Item name="inputValue" label="" style={{ width: 300 }}>
							<Input onPressEnter={e => commonPressEnter(e.target.value)} placeholder="系统商品编码 / 商品唯一码便捷创建"></Input>
						</Form.Item>
					</div>
					<CommonTable
						rowKey="key"
						scroll={{ y: `calc(100vh - 250px)` }}
						columns={columns}
						dataSource={goodsList}
						pagination={false}
					/>
				</Form>
			</div>
			{addVisible == 1 && <GoodsListModal onGoodsSkuListSelected={handleChildValue} {...CheckGoodsModalProps} />}
		</CommonModal>
	);
};

export default AddWarehouseOrderModal;
